package org.itboys.shop.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Post {
	public static String sendHttpPOSTRequest(String httpUrl,
				HashMap<String, String> params) {
			String result = null;
			DefaultHttpClient httpClient = new DefaultHttpClient();// 创建httpClient对象
			try {
				HttpPost httpPost = new HttpPost(httpUrl);
				List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
				if (null != params) {
					Set<String> keys = params.keySet();
					for (String key : keys) {
						String value = params.get(key);
						httpParams.add(new BasicNameValuePair(key, value));
					}
					UrlEncodedFormEntity FormEntity = new UrlEncodedFormEntity(
							httpParams, "UTF-8");
					httpPost.setEntity(FormEntity);
				}
	
				HttpResponse response = httpClient.execute(httpPost);// 获得response对象
				int resStatu = response.getStatusLine().getStatusCode();// 返回码
				// System.out.println(resStatu);
				if (resStatu == HttpStatus.SC_OK) {// 200正常 其它就不合错误
					System.out.println("200");
					HttpEntity entity = response.getEntity(); // 获得响应实体
					if (entity != null) {
						result = EntityUtils.toString(entity, "UTF-8");// 获得http相应body
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				httpClient.getConnectionManager().shutdown();
			}
			return result;
		}
}

